﻿using clf.weighing.entity;
using HandyControl.Controls;
using MyHelper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using Brushes = System.Windows.Media.Brushes;

namespace weighing
{
    /// <summary>
    /// BillEditWindow.xaml 的交互逻辑
    /// </summary>
    public partial class BillEditWindow : GlowWindow
    {
        #region  variables
        private WeighingBillVo? currBillVo;
        private CarInfoVo? currCarVo;
        private CompanyVo? sendCompanyVo;
        private CompanyVo? receiverCompanyVo;
        private MaterialVo? materialVo;

        private bool isFristBindValue = false;
        private bool isSaving = false;
        #endregion

        public Action<bool>? OnChanged { get; set; }

        public BillEditWindow(WeighingBillVo? billVo)
        {
            InitializeComponent();


            CommonFunction.ShowCustomIcon(this);

            if (billVo == null)
            {
                CommonFunction.AlertInfo("传入的参数不正确，窗口将关闭。");
                this.Close();
            }
            currBillVo = billVo;
        }

        #region  win event
        private void Bill_Edit_Window_Loaded(object sender, RoutedEventArgs e)
        {
            //动态插入备用字段，并保存修改后的值
            CreateBackFillUI();
        }

        private void Bill_Edit_Window_ContentRendered(object sender, EventArgs e)
        {
            SetItemSource();
            BindValue();
            SetBackFieldValue();
            SetBackground();
            ChangerUi();

            ShowOrHidePricePanel();

            if (this.PricePanel.Visibility == Visibility.Visible)
            {
                var m = MaterialDao.Instance.FindById(currBillVo?.MaterialId ?? 0);
                if (m == null)
                {
                    //material no add
                    this.TempPriceTb.IsReadOnly = false;
                }
                else
                {
                    if (currBillVo?.Type == (int)WeightingBillType.Buy)
                    {
                        if (App.Config.WeighingConfig.InNecessaryMaterial)
                        {
                            this.TempPriceTb.IsReadOnly = !m.allowInputBuyPrice;
                        }
                        else
                        {
                            this.TempPriceTb.IsReadOnly = false;
                        }                        
                    }
                    else
                    {
                        if (App.Config.WeighingConfig.OutNecessaryMaterial)
                        {
                            // Sale
                            this.TempPriceTb.IsReadOnly = !m.allowInputSalePrice;
                        }
                        else
                        {
                            this.TempPriceTb.IsReadOnly = false;
                        }                        
                    }
                }
            }
        }

        private void Bill_Edit_Window_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            switch (e.Key)
            {
                case Key.Escape:
                    this.Close();
                    break;
            }
        }

        private void Bill_Edit_Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {

        }
        #endregion


        #region backup filed

        /// <summary>
        /// 修改创建 备用字段的UI
        /// </summary>
        private void CreateBackFillUI()
        {
            List<BackupBillField> backupBills = BackupBillFieldDao.Instance.SelectAllByType(currBillVo.Type);
            if (backupBills == null || backupBills.Count == 0)
            {
                this.backFieldPanel.Children.Clear();
            }
            else
            {
                this.backFieldPanel.Children.Clear();
                for (int i = 0; i < backupBills.Count; i++)
                {
                    var item = backupBills[i];
                    int w = item.width < 200 ? 200 : item.width;
                    w = item.width > 400 ? 400 : item.width;
                    if (item.isEnable == 1)
                    {
                        if (item.controlType == (int)BackFieldControlType.Combox)
                        {
                            var combobox = new System.Windows.Controls.ComboBox()
                            {
                                Name = item.fiedName + "CB",
                                Style = FindResource("ComboBoxExtend") as Style,
                                Margin = new Thickness(0, 2, 0, 2),
                                HorizontalAlignment = System.Windows.HorizontalAlignment.Left,
                                MinWidth = 100,
                                MaxWidth = 400,
                                IsEditable = true,
                                MaxDropDownHeight = 300,
                                Width = w,
                                FontSize = 14
                            };
                            InfoElement.SetTitle(combobox, item.displayName);
                            InfoElement.SetTitlePlacement(combobox, HandyControl.Data.TitlePlacementType.Left);
                            InfoElement.SetTitleWidth(combobox, new GridLength(Convert.ToDouble(item.titleWidth)));

                            this.backFieldPanel.Children.Add(combobox);
                        }
                        else
                        {
                            var textBox = new System.Windows.Controls.TextBox()
                            {
                                Name = item.fiedName + "TB",
                                Style = FindResource("TextBoxExtend") as Style,
                                Margin = new Thickness(0, 2, 0, 2),
                                HorizontalAlignment = System.Windows.HorizontalAlignment.Left,
                                MinWidth = 100,
                                MaxWidth = 400,
                                Width = w,
                                FontSize = 14
                            };
                            InfoElement.SetTitle(textBox, item.displayName);
                            InfoElement.SetTitlePlacement(textBox, HandyControl.Data.TitlePlacementType.Left);
                            InfoElement.SetTitleWidth(textBox, new GridLength(Convert.ToDouble(item.titleWidth)));

                            this.backFieldPanel.Children.Add(textBox);
                        }
                    }
                }
            }
        }


        /// <summary>
        /// 设置备用字段的值
        /// </summary>
        private bool SetBackFieldValue()
        {
            if (this.backFieldPanel.Children.Count == 0) return true;
            for (int i = 0; i < this.backFieldPanel.Children.Count; i++)
            {
                try
                {
                    var child = this.backFieldPanel.Children[i] as System.Windows.Controls.TextBox;
                    if (child != null)
                    {
                        var name = child.Name.Replace("TB", "");
                        if (name == Constant.BackfieldName.BackString1)
                        {
                            child.Text = currBillVo.BackupString1;
                        }
                        else if (name == Constant.BackfieldName.BackString2)
                        {
                            child.Text = currBillVo.BackupString2;
                        }
                        else if (name == Constant.BackfieldName.BackString3)
                        {
                            child.Text = currBillVo.BackupString3;
                        }
                        else if (name == Constant.BackfieldName.BackString4)
                        {
                            child.Text = currBillVo.BackupString4;
                        }
                        else if (name == Constant.BackfieldName.BackString5)
                        {
                            child.Text = currBillVo.BackupString5;
                        }
                        else if (name == Constant.BackfieldName.BackInt1)
                        {
                            child.Text = currBillVo.BackupInt1.ToString();
                        }
                        else if (name == Constant.BackfieldName.BackInt2)
                        {
                            child.Text = currBillVo.BackupInt2.ToString();
                        }
                        else if (name == Constant.BackfieldName.BackInt3)
                        {
                            child.Text = currBillVo.BackupInt3.ToString();
                        }
                        else if (name == Constant.BackfieldName.BackInt4)
                        {
                            child.Text = currBillVo.BackupInt4.ToString();
                        }
                        else if (name == Constant.BackfieldName.BackInt5)
                        {
                            child.Text = currBillVo.BackupInt5.ToString();
                        }
                        else if (name == Constant.BackfieldName.BackDecimal1)
                        {
                            child.Text = currBillVo.BackupDecimal1.ToString();
                        }
                        else if (name == Constant.BackfieldName.BackDecimal2)
                        {
                            child.Text = currBillVo.BackupDecimal2.ToString();
                        }
                        else if (name == Constant.BackfieldName.BackDecimal3)
                        {
                            child.Text = currBillVo.BackupDecimal3.ToString();
                        }
                        else if (name == Constant.BackfieldName.BackDecimal4)
                        {
                            child.Text = currBillVo.BackupDecimal4.ToString();
                        }
                        else if (name == Constant.BackfieldName.BackDecimal5)
                        {
                            child.Text = currBillVo.BackupDecimal5.ToString();
                        }
                    }
                    else
                    {
                        //child is null means control is  ComboBox
                        var cb = this.backFieldPanel.Children[i] as System.Windows.Controls.ComboBox;
                        if (cb != null)
                        {
                            var name = cb.Name.Replace("CB", "");
                            if (name == Constant.BackfieldName.BackString1)
                            {
                                cb.Text = currBillVo.BackupString1;
                            }
                            else if (name == Constant.BackfieldName.BackString2)
                            {
                                cb.Text = currBillVo.BackupString2;
                            }
                            else if (name == Constant.BackfieldName.BackString3)
                            {
                                cb.Text = currBillVo.BackupString3;
                            }
                            else if (name == Constant.BackfieldName.BackString4)
                            {
                                cb.Text = currBillVo.BackupString4;
                            }
                            else if (name == Constant.BackfieldName.BackString5)
                            {
                                cb.Text = currBillVo.BackupString5;
                            }
                            else if (name == Constant.BackfieldName.BackInt1)
                            {
                                cb.Text = currBillVo.BackupInt1.ToString();
                            }
                            else if (name == Constant.BackfieldName.BackInt2)
                            {
                                cb.Text = currBillVo.BackupInt2.ToString();
                            }
                            else if (name == Constant.BackfieldName.BackInt3)
                            {
                                cb.Text = currBillVo.BackupInt3.ToString();
                            }
                            else if (name == Constant.BackfieldName.BackInt4)
                            {
                                cb.Text = currBillVo.BackupInt4.ToString();
                            }
                            else if (name == Constant.BackfieldName.BackInt5)
                            {
                                cb.Text = currBillVo.BackupInt5.ToString();
                            }
                            else if (name == Constant.BackfieldName.BackDecimal1)
                            {
                                cb.Text = currBillVo.BackupDecimal1.ToString();
                            }
                            else if (name == Constant.BackfieldName.BackDecimal2)
                            {
                                cb.Text = currBillVo.BackupDecimal2.ToString();
                            }
                            else if (name == Constant.BackfieldName.BackDecimal3)
                            {
                                cb.Text = currBillVo.BackupDecimal3.ToString();
                            }
                            else if (name == Constant.BackfieldName.BackDecimal4)
                            {
                                cb.Text = currBillVo.BackupDecimal4.ToString();
                            }
                            else if (name == Constant.BackfieldName.BackDecimal5)
                            {
                                cb.Text = currBillVo.BackupDecimal5.ToString();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Growl.Error("输入有错：" + ex.Message);
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 获取备用字段的值
        /// </summary>
        private bool GetBackFieldValue()
        {
            if (this.backFieldPanel.Children.Count == 0) return true;
            for (int i = 0; i < this.backFieldPanel.Children.Count; i++)
            {
                try
                {
                    var child = this.backFieldPanel.Children[i] as System.Windows.Controls.TextBox;
                    if (child != null)
                    {
                        var name = child.Name.Replace("TB", "");
                        if (name == Constant.BackfieldName.BackString1)
                        {
                            currBillVo.BackupString1 = child.Text?.Trim();
                        }
                        else if (name == Constant.BackfieldName.BackString2)
                        {
                            currBillVo.BackupString2 = child.Text?.Trim();
                        }
                        else if (name == Constant.BackfieldName.BackString3)
                        {
                            currBillVo.BackupString3 = child.Text?.Trim();
                        }
                        else if (name == Constant.BackfieldName.BackString4)
                        {
                            currBillVo.BackupString4 = child.Text?.Trim();
                        }
                        else if (name == Constant.BackfieldName.BackString5)
                        {
                            currBillVo.BackupString5 = child.Text?.Trim();
                        }
                        else if (name == Constant.BackfieldName.BackInt1)
                        {

                            currBillVo.BackupInt1 = Convert.ToInt32(child.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackInt2)
                        {

                            currBillVo.BackupInt2 = Convert.ToInt32(child.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackInt3)
                        {
                            currBillVo.BackupInt3 = Convert.ToInt32(child.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackInt4)
                        {

                            currBillVo.BackupInt4 = Convert.ToInt32(child.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackInt5)
                        {
                            currBillVo.BackupInt5 = Convert.ToInt32(child.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackDecimal1)
                        {
                            currBillVo.BackupDecimal1 = Convert.ToDecimal(child.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackDecimal2)
                        {
                            currBillVo.BackupDecimal2 = Convert.ToDecimal(child.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackDecimal3)
                        {
                            currBillVo.BackupDecimal3 = Convert.ToDecimal(child.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackDecimal4)
                        {
                            currBillVo.BackupDecimal4 = Convert.ToDecimal(child.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackDecimal5)
                        {
                            currBillVo.BackupDecimal5 = Convert.ToDecimal(child.Text.Trim());
                        }
                    }
                    else
                    {
                        var cb = this.backFieldPanel.Children[i] as System.Windows.Controls.ComboBox;
                        if (cb != null)
                        {
                            var name = cb.Name.Replace("CB", "");
                            string value = cb.Text?.Trim();
                            if (name == Constant.BackfieldName.BackString1)
                            {
                                currBillVo.BackupString1 = value;
                            }
                            else if (name == Constant.BackfieldName.BackString2)
                            {
                                currBillVo.BackupString2 = value;
                            }
                            else if (name == Constant.BackfieldName.BackString3)
                            {
                                currBillVo.BackupString3 = value;
                            }
                            else if (name == Constant.BackfieldName.BackString4)
                            {
                                currBillVo.BackupString4 = value;
                            }
                            else if (name == Constant.BackfieldName.BackString5)
                            {
                                currBillVo.BackupString5 = value;
                            }
                            else if (name == Constant.BackfieldName.BackInt1)
                            {

                                currBillVo.BackupInt1 = Convert.ToInt32(value);
                            }
                            else if (name == Constant.BackfieldName.BackInt2)
                            {

                                currBillVo.BackupInt2 = Convert.ToInt32(value);
                            }
                            else if (name == Constant.BackfieldName.BackInt3)
                            {
                                currBillVo.BackupInt3 = Convert.ToInt32(value);
                            }
                            else if (name == Constant.BackfieldName.BackInt4)
                            {

                                currBillVo.BackupInt4 = Convert.ToInt32(value);
                            }
                            else if (name == Constant.BackfieldName.BackInt5)
                            {
                                currBillVo.BackupInt5 = Convert.ToInt32(value);
                            }
                            else if (name == Constant.BackfieldName.BackDecimal1)
                            {
                                currBillVo.BackupDecimal1 = Convert.ToDecimal(value);
                            }
                            else if (name == Constant.BackfieldName.BackDecimal2)
                            {
                                currBillVo.BackupDecimal2 = Convert.ToDecimal(value);
                            }
                            else if (name == Constant.BackfieldName.BackDecimal3)
                            {
                                currBillVo.BackupDecimal3 = Convert.ToDecimal(value);
                            }
                            else if (name == Constant.BackfieldName.BackDecimal4)
                            {
                                currBillVo.BackupDecimal4 = Convert.ToDecimal(value);
                            }
                            else if (name == Constant.BackfieldName.BackDecimal5)
                            {
                                currBillVo.BackupDecimal5 = Convert.ToDecimal(value);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Growl.Error("输入有错：" + ex.Message, "edit");
                    return false;
                }
            }
            return true;
        }

        #endregion


        private void SetItemSource()
        {
            List<Company> companies = CompanyDao.Instance.GetList();
            var CompanySource = companies?.Select((i) => { return new CompanyVo(i); });
            this.sendCompanyCb.ItemsSource = CompanySource;
            this.RecevieCompanyCb.ItemsSource = CompanySource;

            List<Material> ms =MaterialDao.Instance.GetList();
            var mSource = ms?.Select((i) => { return new MaterialVo(i); });
            this.materialCb.ItemsSource = mSource;

            List<CarInfo> cs =CarDao.Instance.GetList();
            var cSource = cs?.Select((i) => { return new CarInfoVo(i); });
            this.carNumberCb.ItemsSource = cSource;

            //this.remarkCb.ItemsSource = ;
            //this.decuDescCb.ItemsSource = App.decuationDesList;
        }


        private void BindValue()
        {
            isFristBindValue = true;
            this.BillInfoTb.Text = "编号：" + currBillVo?.Number;
            this.billnumberTb.Text = currBillVo.Number;
            bool isSet = false;
            // send company
            var cvos = this.sendCompanyCb.ItemsSource as List<CompanyVo>;
            if (cvos == null || cvos.Count <= 0)
            {
                this.sendCompanyCb.Text = currBillVo.SendCompanyName ?? "";
            }
            else
            {
                for (int i = 0; i < cvos.Count; i++)
                {
                    var item = cvos[i];
                    if (item.Id == currBillVo.SendCompanyId)
                    {
                        this.sendCompanyCb.SelectedIndex = i;
                        isSet = true;
                        break;
                    }
                }
            }
            if (isSet == false || !currBillVo.SendCompanyName.IsNullOrEmpty())
            {
                this.sendCompanyCb.Text = currBillVo.SendCompanyName ?? "";
            }
            isSet = false;
            // recevie company
            var rcvos = this.RecevieCompanyCb.ItemsSource as List<CompanyVo>;
            if (rcvos == null || rcvos.Count <= 0)
            {
                this.RecevieCompanyCb.Text = currBillVo.ReceiveCompanyName ?? "";
            }
            else
            {
                for (int i = 0; i < rcvos.Count; i++)
                {
                    var item = rcvos[i];
                    if (item.Id == currBillVo.ReceiveCompanyId)
                    {
                        this.RecevieCompanyCb.SelectedIndex = i;
                        isSet = true;
                        break;
                    }
                }
            }
            if (isSet == false || !string.IsNullOrEmpty(currBillVo.ReceiveCompanyName))
            {
                this.RecevieCompanyCb.Text = currBillVo.ReceiveCompanyName ?? "";
            }
            isSet = false;
            //material
            var mvos = this.materialCb.ItemsSource as List<MaterialVo>;
            if (mvos == null || mvos.Count <= 0)
            {
                this.materialCb.Text = currBillVo.MaterialName ?? "";
            }
            else
            {
                for (int i = 0; i < mvos.Count; i++)
                {
                    var item = mvos[i];
                    if (item.Id == currBillVo.MaterialId)
                    {
                        this.materialCb.SelectedIndex = i;
                        isSet = true;
                        break;
                    }
                }
            }
            if (isSet == false || !currBillVo.MaterialName.IsNullOrEmpty())
            {
                this.materialCb.Text = currBillVo.MaterialName ?? "";
            }
            isSet = false;
            // car 
            var carvos = this.carNumberCb.ItemsSource as List<CarInfoVo>;
            if (carvos == null || carvos.Count <= 0)
            {
                this.carNumberCb.Text = currBillVo.CarNumber ?? "";
            }
            else
            {
                for (int i = 0; i < carvos.Count; i++)
                {
                    var item = carvos[i];
                    if (item.CarNumber == currBillVo.CarNumber)
                    {
                        this.carNumberCb.SelectedIndex = i;
                        this.driverTb.Text = item.Driver;
                        this.phoneTb.Text = item.DriverMobile;
                        currCarVo = item;
                        isSet = true;
                        break;
                    }
                }
            }
            if (isSet == false || !currBillVo.CarNumber.IsNullOrEmpty())
            {
                this.carNumberCb.Text = currBillVo.CarNumber ?? "";
                this.driverTb.Text = currBillVo.Driver ?? "";
                this.phoneTb.Text = currBillVo.DriverMobile ?? "";
            }
            isSet = false;

            this.sendNetWeightTb.Text = currBillVo.SendNetWeight.ToString();
            this.grossWeightTb.Text = currBillVo.GrossWeight.ToString();
            this.TraeWeightTb.Text = currBillVo.TraeWeight.ToString();
            this.netWeightTb.Text = currBillVo.NetWeight.ToString();
            this.decuationWeightTb.Text = currBillVo.DecuationWeight.ToString();
            this.decuDescCb.Text = currBillVo.DecuationDescription;
            this.diffWeightTb.Text = currBillVo.DiffWeight.ToString();
            this.remarkCb.Text = currBillVo.Remark;
            this.userTb.Text = currBillVo.AddUserName;

            this.TempPriceTb.Text = currBillVo.Price.ToString();
            this.TotalMoneyTb.Text = currBillVo.TotalMoney.ToString();
            this.ReceiveMoneyTb.Text = currBillVo.ReceiveMoney.ToString();
            this.MoneyTypeCb.SelectedIndex = (int)currBillVo.MoneyType;

            isFristBindValue = false;
        }


        private void SetBackground()
        {
            if (currBillVo.Type == (int)WeightingBillType.Buy)
            {
                this.inputPanel.Background = Brushes.LemonChiffon;
            }
            else
            {
                this.inputPanel.Background = Brushes.LightSalmon;
            }
        }

        private void ChangerUi()
        {
            if (currBillVo?.Type == (int)WeightingBillType.Buy)
            {
                this.diffWeightTb.Visibility = Visibility.Visible;
                this.decuationWeightTb.Visibility = Visibility.Visible;
                this.decuDescCb.Visibility = Visibility.Visible;
                this.sendNetWeightTb.Visibility = Visibility.Visible;
                if (App.CurrentUser?.roleType < (int)UserRoleType.WeighingManager)
                {
                    this.sendNetWeightTb.IsEnabled = false;
                    this.decuationWeightTb.IsEnabled = false;
                }
                else
                {
                    this.sendNetWeightTb.IsEnabled = true;
                    this.decuationWeightTb.IsEnabled = true;
                }
            }
            else
            {
                this.diffWeightTb.Visibility = Visibility.Collapsed;
                this.decuationWeightTb.Visibility = Visibility.Collapsed;
                this.decuDescCb.Visibility = Visibility.Collapsed;
                this.sendNetWeightTb.Visibility = Visibility.Collapsed;
            }

            if (App.CurrentUser?.roleType < (int)UserRoleType.WeighingManager)
            {
                this.grossWeightTb.IsEnabled = false;
                this.TraeWeightTb.IsEnabled = false;
                this.netWeightTb.IsEnabled = false;
            }
            else
            {
                this.grossWeightTb.IsEnabled = true;
                this.TraeWeightTb.IsEnabled = true;
                this.netWeightTb.IsEnabled = true;
            }
        }

        #region Supply 
        private bool isSupplySelected = false;
        private void SupplyCb_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (isFristBindValue) return;

            if(currBillVo?.Type == (int)WeightingBillType.Buy)
            {
                //In Necessary Send  not must ,not to search
                if (App.Config.WeighingConfig.InNecessarySend == false) return;
            }
            else
            {
                //Out Necessary Send  not must ,not to search
                if (App.Config.WeighingConfig.OutNecessarySend == false) return;
            }

            String text = this.sendCompanyCb.Text;
            if (text != "null") { text = text.Trim(); };
            if (text.Length < 2)
            {
                isSupplySelected = false;
                this.sendCompanyCb.IsDropDownOpen = false;

                receiverCompanyVo = null;
                currBillVo.ReceiveCompanyId = 0;
                currBillVo.ReceiveCompanyName = String.Empty;
            }
            if (isSupplySelected == true)
            {
                return;
            }
            if (text.Length >= 2)
            {
                List<Company> list = CompanyDao.Instance.SelectByNameOrFirstCaseLike(text);
                if (list.Count <= 0)
                {
                    isSupplySelected = false;
                }
                sendCompanyCb.ItemsSource = list.Select((i) => { return new CompanyVo(i); });
                if (sendCompanyCb.ItemsSource != null)
                {
                    this.sendCompanyCb.IsDropDownOpen = true;
                }
            }

        }
        private void SupplyCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sendCompanyCb.SelectedIndex == -1)
            {
                this.sendCompanyCb.Text = "";
                sendCompanyVo = null;
                return;
            }
            isSupplySelected = true;
            sendCompanyVo = sendCompanyCb.SelectedItem as CompanyVo;
            if (sendCompanyVo != null)
            {
                if (CheckSupplyCustomer() == false)
                {
                    string msg = "发货公司和收货公司不能是同一个！";
                    CommonFunction.SpeakAsync(msg);
                    CommonFunction.AlertInfo(msg);
                    this.sendCompanyCb.Text = "";
                    sendCompanyVo = null;
                }
                else
                {
                    currBillVo.SendCompanyId = sendCompanyVo.Id;
                    currBillVo.SendCompanyName = sendCompanyVo.FullName;
                    //this.SendYardCb.ItemsSource = null;
                    //ShowSendYard();
                }
            }
        }

        #endregion

        #region Receiver Company
        private bool isSelectReceiveCompany = false;
        private void ReceiverCompanyCb_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (isFristBindValue) return;
           
            if (currBillVo.Type == (int)WeightingBillType.Buy)
            {
                //In Necessary Receive not must ,not to search
                if (App.Config.WeighingConfig.InNecessaryReceive == false) return;
            }
            else
            {
                //Out Necessary Receive  not must ,not to search
                if (App.Config.WeighingConfig.OutNecessaryReceive == false) return;
            }

            String text = this.RecevieCompanyCb.Text;
            if (text != null) { text = text.Trim(); };
            if (text.Length < 2)
            {
                isSelectReceiveCompany = false;
                this.RecevieCompanyCb.IsDropDownOpen = false;

                receiverCompanyVo = null;
                currBillVo.ReceiveCompanyId = 0;
                currBillVo.ReceiveCompanyName = String.Empty;
            }
            if (isSelectReceiveCompany == true) { return; }
            if (text.Length >= 2)
            {
                List<Company> list = CompanyDao.Instance.SelectByNameOrFirstCaseLike(text);
                if (list.Count > 0)
                {
                    isSelectReceiveCompany = true;
                }
                this.RecevieCompanyCb.ItemsSource = list.Select((i) => { return new CompanyVo(i); });
                if (this.RecevieCompanyCb.ItemsSource != null)
                {
                    this.RecevieCompanyCb.IsDropDownOpen = true;
                }
                else
                {
                    this.RecevieCompanyCb.IsDropDownOpen = false;
                }
            }
        }
        private void ReceiverCompanyCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (RecevieCompanyCb.SelectedIndex == -1)
            {
                RecevieCompanyCb.Text = "";
                receiverCompanyVo = null;
                return;
            };
            isSelectReceiveCompany = true;
            receiverCompanyVo = RecevieCompanyCb.SelectedItem as CompanyVo;
            if (receiverCompanyVo != null)
            {
                if (CheckSupplyCustomer() == false)
                {
                    string msg = "发货公司和收货公司不能是同一个！";
                    CommonFunction.SpeakAsync(msg);
                    CommonFunction.AlertInfo(msg);
                    RecevieCompanyCb.Text = "";
                    receiverCompanyVo = null;
                }
                else
                {
                    currBillVo.ReceiveCompanyId = receiverCompanyVo.Id;
                    currBillVo.ReceiveCompanyName = receiverCompanyVo.FullName;
                    //this.ReceiverYardCb.ItemsSource = null;
                    //ShowReceivedYard();
                }
            }
        }
        /// <summary>
        /// 供应商和客户是不能是同一个公司
        /// </summary>
        /// <returns></returns>
        private bool CheckSupplyCustomer()
        {
            if(currBillVo.Type == (int)WeightingBillType.Buy)
            {
                if (App.Config.WeighingConfig.InNotSameCompany)
                {
                    if (receiverCompanyVo != null && sendCompanyVo != null)
                    {
                        if (receiverCompanyVo.Id == sendCompanyVo.Id)
                        {
                            return false;
                        }
                    }
                    return true;
                }
            }
            else
            {
                if (App.Config.WeighingConfig.OutNotSameCompany)
                {
                    if (receiverCompanyVo != null && sendCompanyVo != null)
                    {
                        if (receiverCompanyVo.Id == sendCompanyVo.Id)
                        {
                            return false;
                        }
                    }
                    return true;
                }
            }
            return true ;
           
        }
        #endregion

        #region Material 
        private bool isSelectMaterial = false;
        private void MaterialNameCb_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (isFristBindValue) return;
         

            if (currBillVo?.Type == (int)WeightingBillType.Buy)
            {
                //In Necessary Material  not must ,not to search
                if (App.Config.WeighingConfig.InNecessaryMaterial == false) return;
            }
            else
            {
                //Out Necessary Material  not must ,not to search
                if (App.Config.WeighingConfig.OutNecessaryMaterial == false) return;
            }

            String text = this.materialCb.Text;
            if (text != null) { text = text.Trim(); };
            if (text.Length < 2)
            {
                isSelectMaterial = false;
                this.materialCb.IsDropDownOpen = false;

                materialVo = null;
                currBillVo.MaterialId = 0;
                currBillVo.MaterialName = "";
            }
            if (isSelectMaterial == true) { return; }
            if (text.Length >= 2)
            {
                List<Material> list = MaterialDao.Instance.SelectByNameOrFirstCaseLike(text);
                if (list.Count > 0)
                {
                    isSelectMaterial = true;
                }

                this.materialCb.ItemsSource = list.Select((i) => { return new MaterialVo(i); });
                if (this.materialCb.ItemsSource != null)
                {
                    this.materialCb.IsDropDownOpen = true;
                }
                else
                {
                    this.materialCb.IsDropDownOpen = false;
                }
            }
        }

        private void MaterialNameCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (materialCb.SelectedIndex != -1)
            {
                isSelectMaterial = true;
                materialVo = (MaterialVo)materialCb.SelectedItem;
                currBillVo.MaterialId = materialVo.Id;
                currBillVo.MaterialName = materialVo.Name;
            }
        }
        #endregion

        #region CarInfo 
        private bool isCarInfoSelectioned = false;
        private void CarNumberCb_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (isFristBindValue) return;
        
            if (currBillVo.Type == (int)WeightingBillType.Buy)
            {
                //In Necessary Car  not must ,not to search
                if (App.Config.WeighingConfig.InNecessaryCar == false) return;
            }
            else
            {
                //Out Necessary Material  not must ,not to search
                if (App.Config.WeighingConfig.OutNecessaryCar == false) return;
            }

            String text = this.carNumberCb.Text;
            if (text != null) { text = text.Trim(); };
            if (text.Length <= 0)
            {
                isCarInfoSelectioned = false;
                currCarVo = null;
                this.carNumberCb.IsDropDownOpen = false;
                SetCarInfo();
                return;
            }
            if (isCarInfoSelectioned == true) { return; }

            if (text.Length >= 2)
            {
                List<CarInfo> list = CarDao.Instance.SelectByLike(text);
                if (list.Count > 0)
                {
                    isCarInfoSelectioned = true;
                }
                this.carNumberCb.ItemsSource = list.Select((i) => { return new CarInfoVo(i); });
                if (carNumberCb.ItemsSource != null)
                {
                    this.carNumberCb.IsDropDownOpen = true;
                }
            }
        }

        private void CarNumberCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (carNumberCb.SelectedIndex >= 0)
            {
                currCarVo = (CarInfoVo)carNumberCb.SelectedItem;
                isCarInfoSelectioned = true;
                currBillVo.CarNumber = currCarVo.CarNumber;
                currBillVo.CarId = currCarVo.Id;
                currBillVo.Driver = currCarVo.Driver;
                currBillVo.DriverMobile = currCarVo.DriverMobile;

                SetCarInfo();
            }
            else
            {
                this.currCarVo = null;
                SetCarInfo();
            }
        }

        private void SetCarInfo()
        {
            if (currCarVo != null)
            {
                this.driverTb.Text = currCarVo.Driver;
                this.phoneTb.Text = currCarVo.DriverMobile;
                currBillVo.CarId = currCarVo.Id;
                currBillVo.CarNumber = currCarVo.CarNumber;
                currBillVo.Driver = currCarVo.Driver;
                currBillVo.DriverMobile = currCarVo.DriverMobile;
            }
            else
            {
                this.driverTb.Text = string.Empty;
                this.phoneTb.Text = string.Empty;
                currBillVo.CarId = 0;
                currBillVo.CarNumber = String.Empty;
                currBillVo.Driver = String.Empty;
                currBillVo.DriverMobile = String.Empty;
            }
        }
        #endregion

        #region 输入改变事件
        private void GrossWeightTb_TextChanged(object sender, TextChangedEventArgs e)
        {
            CalcToneValue();
        }

        private void TraeWeightTb_TextChanged(object sender, TextChangedEventArgs e)
        {
            CalcToneValue();
        }
        //扣吨
        private void decuationWeightTb_TextChanged(object sender, TextChangedEventArgs e)
        {
            CalcToneValue();
        }
        //原发净重
        private void SendNetWeightTb_TextChanged(object sender, TextChangedEventArgs e)
        {
            CalcToneValue();
        }
        /// <summary>
        /// 计算吨位  calculating the tonnage of receipt
        /// </summary>
        private void CalcToneValue()
        {
            if (isFristBindValue) return;
            if (this.IsLoaded == false) return;

            decimal gross = 0, trace = 0, net, sendNet = 0, decu = 0, diff;
            try { gross = Convert.ToDecimal(this.grossWeightTb.Text); } catch { }
            try { trace = Convert.ToDecimal(this.TraeWeightTb.Text); } catch { }
            currBillVo.GrossWeight = gross;
            currBillVo.TraeWeight = trace;
            if (currBillVo.Type == (int)WeightingBillType.Buy)
            {
                try { sendNet = Convert.ToDecimal(this.sendNetWeightTb.Text); } catch { }
                try { decu = Convert.ToDecimal(this.decuationWeightTb.Text); } catch { }
                net = Math.Round(gross - trace - decu, 2); ;
                diff = Math.Round(net - sendNet, 2);
                currBillVo.NetWeight = net;
                currBillVo.SendNetWeight = sendNet;
                currBillVo.DiffWeight = diff;
                currBillVo.DecuationWeight = decu;
                this.diffWeightTb.Text = diff.ToString();
                this.netWeightTb.Text = net.ToString();
            }
            else
            {
                net = Math.Round(gross - trace, 2);
                currBillVo.NetWeight = net;
                currBillVo.DiffWeight = 0;
                this.netWeightTb.Text = net.ToString();
            }
        }
        #endregion


        //保存
        private void SaveBtn_Click(object sender, RoutedEventArgs e)
        {
         
            if (isSaving)
            {
                return;
            }
            isSaving = true;

            if (CheckInput() == false)
            {
                isSaving = false;
                return;
            }
            //重置上传次数，上传修改服务器数据
            currBillVo.UpOfficalStatus = 1;
            if(this.driverTb.Text != currBillVo.Driver)
            {
                currBillVo.Driver = this.driverTb.Text;
            }
            if (this.phoneTb.Text != currBillVo.DriverMobile)
            {
                currBillVo.DriverMobile = this.phoneTb.Text;
            }

            GetBackFieldValue();

            GetPriceValue();

            int res = WeighingBillDao.Instance.Update(currBillVo.mWeighingBill);
            if (res > 0)
            {
                OnChanged?.Invoke(true);
                Growl.Success("保存成功", "edit");
                //print
                if (currBillVo.Status == (int)BillStatus.Finished)
                {
                    new PrintWindow(currBillVo.Id,WeightingBillType.WeighintBill) { 
                        Owner = this
                    }.ShowDialog();
                }
                this.Close();
            }
            else
            {
                Growl.Error("保存失败", "edit");
            }
            isSaving = false;
        }

        //验证输入
        private bool CheckInput()
        {
            if (currBillVo?.Type == (int)WeightingBillType.Sale && App.Config.WeighingConfig.OutNecessarySend)
            {
                if (currBillVo.SendCompanyId == null || currBillVo.SendCompanyId <= 0 || currBillVo.SendCompanyName.IsNullOrEmpty())
                {
                    Growl.Error("请选择发货公司信息", "edit");
                    this.sendCompanyCb.Focus();
                    return false;
                }
            }
            else if (currBillVo?.Type == (int)WeightingBillType.Buy && App.Config.WeighingConfig.OutNecessarySend)
            {
                if (currBillVo.SendCompanyId == null || currBillVo.SendCompanyId <= 0 || currBillVo.SendCompanyName.IsNullOrEmpty())
                {
                    Growl.Error("请选择发货公司信息", "edit");
                    this.sendCompanyCb.Focus();
                    return false;
                }
            }
            else
            {
                currBillVo.SendCompanyId = 0;
                currBillVo.SendCompanyName = this.sendCompanyCb.Text;
            }

        


            if ((currBillVo.Type == (int)WeightingBillType.Buy && App.Config.WeighingConfig.InNecessaryReceive))
            {
                if (currBillVo.ReceiveCompanyId == null || currBillVo.ReceiveCompanyId <= 0 || string.IsNullOrEmpty(currBillVo.ReceiveCompanyName))
                {
                    Growl.Error("请选择收货公司", "edit");
                    this.RecevieCompanyCb.Focus();
                    return false;
                }
            }
            else if (currBillVo.Type == (int)WeightingBillType.Sale && App.Config.WeighingConfig.OutNecessaryReceive)
            {
                if (currBillVo.ReceiveCompanyId == null || currBillVo.ReceiveCompanyId <= 0 || string.IsNullOrEmpty(currBillVo.ReceiveCompanyName))
                {
                    Growl.Error("请选择收货公司", "edit");
                    this.RecevieCompanyCb.Focus();
                    return false;
                }
            }
            else
            {
                currBillVo.ReceiveCompanyId = 0;
                currBillVo.ReceiveCompanyName = this.RecevieCompanyCb.Text;
            }

            //if (string.IsNullOrEmpty(currBillVo.receiveYardId) || string.IsNullOrEmpty(currBillVo.receiveYardName))
            //{
            //    ShowAlert("请选择收货货场");
            //    this.ReceiverYardCb.Focus();
            //    return false;
            //}

            if (InfoElement.GetNecessary(this.materialCb) == true)
            {
                if (currBillVo.MaterialId == null || currBillVo.MaterialId <= 0 || string.IsNullOrEmpty(currBillVo.MaterialName))
                {
                    Growl.Error("请选择物资名称", "edit");
                    this.materialCb.Focus();
                    return false;
                }
            }
            else
            {
                if (materialVo != null)
                {
                    currBillVo.MaterialId = materialVo.Id;
                    currBillVo.MaterialName = materialVo.Name;
                }
                else
                {
                    currBillVo.MaterialId = 0;
                    currBillVo.MaterialName = this.materialCb.Text;
                }

            }
            if (currBillVo.CarId == null || currBillVo.CarId <= 0 || string.IsNullOrEmpty(currBillVo.CarNumber))
            {
                if (RegexHelper.IsVehicleNumber(this.carNumberCb.Text))
                {
                    var car = new CarInfo()
                    {
                        id = IdHelper.LongID,
                        carNumber = this.carNumberCb.Text,
                        addTime = DateTime.Now,
                        addUserId = App.CurrentUser.id,
                        addUserName = App.CurrentUser.name,
                        remark = "自动添加",
                        traeWeight = 0,
                        driver = this.driverTb.Text,
                        driverMobile = this.phoneTb.Text
                    };
                    currBillVo.CarId = car.id;
                    currBillVo.CarNumber = car.carNumber;
                    currBillVo.Driver = car.driver;
                    currBillVo.DriverMobile = car.driverMobile;
                }
                else
                {
                    if (currBillVo.Type == (int)WeightingBillType.Buy)
                    {
                        if (App.Config.WeighingConfig.InCheckCarNumber)
                        {

                            Growl.Warning("请输入车辆信息");
                            this.carNumberCb.Focus();
                            return false;
                        }
                        else
                        {
                            currBillVo.CarId = 0;
                            currBillVo.CarNumber = this.carNumberCb.Text;
                            currBillVo.Driver = this.driverTb.Text;
                            currBillVo.DriverMobile = this.phoneTb.Text;
                        }
                    }
                    else if (currBillVo.Type == (int)WeightingBillType.Sale)
                    {
                        if (App.Config.WeighingConfig.OutCheckCarNumber)
                        {
                            Growl.Warning("请输入车辆信息");
                            this.carNumberCb.Focus();
                            return false;
                        }
                        else
                        {
                            currBillVo.CarId = 0;
                            currBillVo.CarNumber = this.carNumberCb.Text;
                            currBillVo.Driver = this.driverTb.Text;
                            currBillVo.DriverMobile = this.phoneTb.Text;
                        }
                    }
                }
            }

            if (currBillVo.Status == (int)BillStatus.Finished)
            {

                if (currBillVo.GrossWeight < 0 || currBillVo.TraeWeight < 0 || currBillVo.NetWeight <= 0)
                {
                    Growl.Warning("重量吨位不正确");
                    return false;
                }
            }

            ////入场时间 
            //if (this.startDateTime.SelectedDateTime == null)
            //{
            //    Growl.Error("请选择入场时间", "edit");
            //    return false;
            //}
            //if (this.startDateTime.SelectedDateTime >= DateTime.Now)
            //{
            //    Growl.Error("入场时间错误", "edit");
            //    return false;
            //}
            //currBillVo.inTime = this.startDateTime.SelectedDateTime;
            ////出场时间
            //if (this.endDateTime.SelectedDateTime == null)
            //{

            //    Growl.Error("请选择出场时间", "edit");
            //    return false;
            //}
            //if (this.endDateTime.SelectedDateTime > DateTime.Now)
            //{
            //    Growl.Error("出场时间错误，不能大于当前时间。", "edit");
            //    return false;
            //}

            currBillVo.Remark = this.remarkCb.Text;
            currBillVo.DecuationDescription = this.decuDescCb.Text;

            return true;
        }


        #region 价格 计算机
        private void TempPriceTb_TextChanged(object sender, TextChangedEventArgs e)
        {
            CalcMaterialMoney();
        }

        private void CalcMaterialMoney()
        {
            if (!IsLoaded || PricePanel.IsVisible == false) return;
            //不管磅单是显示或者 不显示 都要计算 
            decimal price = 0;
            try
            {
                price = Convert.ToDecimal(this.TempPriceTb.Text.Trim());
            }
            catch (Exception ex)
            {
                //    if(PricePanel.IsVisible)
                //        Growl.Error("输入的单价不正确，以0计算：" + ex.Message,"main");
            }

            var totalMoney = (decimal)Math.Round((double)(price * currBillVo.NetWeight ?? 0), 3, MidpointRounding.AwayFromZero);


            this.TotalMoneyTb.Text = totalMoney + "";

            string receiveMoneyStr = this.ReceiveMoneyTb.Text.Trim();
            if (receiveMoneyStr.IsNullOrEmpty() || receiveMoneyStr.Equals("0")
                || receiveMoneyStr.Equals("0.0")
                || receiveMoneyStr.Equals("0.00")
                || receiveMoneyStr.Equals("0.000"))
            {
                this.ReceiveMoneyTb.Text = totalMoney + "";
            }

        }
        public void ShowOrHidePricePanel()
        {            
            //修改时不存在一次过磅和两次过磅的区别
            if (currBillVo.Type == (int)WeightingBillType.Buy)
            {
                if (App.Config.BillPrintConfig.InShowCalculate)
                {
                    this.PricePanel.Visibility = Visibility.Visible;
                }
                else
                {
                    this.PricePanel.Visibility = Visibility.Collapsed;
                }
            }
            else
            {
                if (App.Config.BillPrintConfig.OutShowCalculate)
                {
                    this.PricePanel.Visibility = Visibility.Visible;
                }
                else
                {
                    this.PricePanel.Visibility = Visibility.Collapsed;
                }
            }


        }

        /// <summary>
        /// 获取修改后的收费信息
        /// </summary>
        private void GetPriceValue()
        {
            //价格Panel 没有显示，就没有获取值的必要
            if (this.PricePanel.Visibility == Visibility.Collapsed) return;

            decimal price = 0;
            try
            {
                price = Convert.ToDecimal(this.TempPriceTb.Text);
            }
            catch (Exception)
            {
            }
            currBillVo.Price = price;
            currBillVo.TotalMoney = (decimal)Math.Round((double)(currBillVo.Price * currBillVo.NetWeight ?? 0), 3, MidpointRounding.AwayFromZero);

            
            //pay type
            if (this.MoneyTypeCb.SelectedIndex > -1)
            {
                int index = this.MoneyTypeCb.SelectedIndex;
                currBillVo.MoneyType = (MoneyType)index;
            }
            else
            {
                currBillVo.MoneyType = 0;
            }


            decimal reciveMoney = 0;
            try
            {
                reciveMoney = Convert.ToDecimal(this.ReceiveMoneyTb.Text);
            }
            catch (Exception)
            {
            }
            currBillVo.ReceiveMoney = reciveMoney;
        }

        #endregion       
    }
}
